package com.mr.productclient.service;

import com.mr.productclient.dao.ProductInfoDao;
import com.mr.productclient.entity.ProductInfo;
import com.mr.productclient.exception.CustomException;
import com.mr.productclient.utils.ConstantEnum;
import com.mr.productclient.utils.JsonUtil;
import com.mr.productclient.vo.CartVO;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
* User (作者): MRui
* TODO (描述)：商品服务类
* Data：2018-11-04 17:28
*/
@Service
@Transactional
public class ProductService {

    @Autowired
    private ProductInfoDao dao;
    @Autowired
    private AmqpTemplate amqpTemplate;
    /**
     * 获取一条
     */
    public ProductInfo getOne(String productId){
        ProductInfo productInfo = dao.findById(productId).orElse(null);
        return productInfo;
    }

    /**
     * 列表（分页）
     * @param pageable
     * @return
     */
    public Page<ProductInfo> getAll(Pageable pageable){
        Page<ProductInfo> productInfos = dao.findAll(pageable);
        return productInfos;
    }


    /**
     * 获取上架商品
     * @param status
     * @return
     */
    public List<ProductInfo> getUpAll(int status){
        List<ProductInfo> productStatus = dao.findByProductStatus(status);
        return productStatus;
    }

    /**
     * 保存
     * @param info
     * @return
     */
    public ProductInfo save(ProductInfo info){
        ProductInfo productInfo = dao.save(info);
        return productInfo;
    }
    /**
    * @user (作者)MRui
    * @Description: TODO描述:加库存
    * @date 2018.09.21 21:17
    */
    public void increaseStock(List<CartVO> cartVOList){
        for (CartVO cartVO : cartVOList){
            ProductInfo productInfo = dao.findById(cartVO.getProductId()).get();
            if (productInfo == null){
                throw new CustomException(ConstantEnum.EXCEPTION_PRODUCT_NOT_EXIST);
            }
            int result = productInfo.getProductStock()+cartVO.getProductQuantity();
            productInfo.setProductStock(result);
            dao.save(productInfo);
        }
    }
    /**
    * @user (作者)MRui
    * @Description: TODO描述:减库存完毕后发送mq消息
    * @date 2018.09.21 21:17
    */
    @Transactional
    public void decreaseStock(List<CartVO> cartVOList){
        List<ProductInfo> list = decreaseStockProcess(cartVOList);
        //java8新特性
        /*List<ProductInfo> productInfoList = list.stream().map(e -> {
            ProductInfo productInfo = new ProductInfo();
            BeanUtils.copyProperties(e, productInfo);
            return productInfo;
        }).collect(Collectors.toList());*/
        //发送mq消息
        amqpTemplate.convertAndSend("productInfo", JsonUtil.jacksonToJson(list));
    }
    /**
    * User (作者): MRui
    * TODO (描述)：扣库存
    * Data：2018-11-11 23:57   
    */
    public List<ProductInfo> decreaseStockProcess(List<CartVO> cartVOList){
        List<ProductInfo> list = new ArrayList<>();
        for (CartVO cartVO : cartVOList) {
            ProductInfo productInfo = dao.getOne(cartVO.getProductId());
            if (productInfo == null){
                throw new CustomException(ConstantEnum.EXCEPTION_PRODUCT_NOT_EXIST);
            }
            int result = productInfo.getProductStock()- cartVO.getProductQuantity();
            if (result < 0){
                throw new CustomException(ConstantEnum.EXCEPTION_PRODUCT_STOCK_ERROR);
            }
            productInfo.setProductStock(result);
            dao.save(productInfo);
            list.add(productInfo);
        }
        return list;
    }
    /**
    * User (作者): MRui
    * TODO (描述)：上架
    * Data：2018.09.30 23:14
    */
    public void onSale(String productId){
        ProductInfo productInfo = dao.findById(productId).orElse(null);
        if (productInfo == null){
            throw new CustomException(ConstantEnum.EXCEPTION_PRODUCT_NOT_EXIST);
        }
        if (productInfo.getProductStatusMessage().equals(ConstantEnum.PRODUCT_UP)){
            throw new CustomException(ConstantEnum.PRODUCT_STATUS_ERROR);
        }
        //更新
        productInfo.setProductStatus(ConstantEnum.PRODUCT_UP.getCode());
        dao.save(productInfo);
    }
    /**
    * User (作者): MRui
    * TODO (描述)：下架
    * Data：2018.09.30 23:15
    */
    public void offSale(String productId){
        ProductInfo productInfo = dao.findById(productId).orElse(null);
        if (productInfo == null){
            throw new CustomException(ConstantEnum.EXCEPTION_PRODUCT_NOT_EXIST);
        }
        if (productInfo.getProductStatusMessage().equals(ConstantEnum.PRODUCT_DOWN)){
            throw new CustomException(ConstantEnum.PRODUCT_STATUS_ERROR);
        }
        //更新
        productInfo.setProductStatus(ConstantEnum.PRODUCT_DOWN.getCode());
        dao.save(productInfo);
    }

    /**
    * User (作者): MRui
    * TODO (描述)：根据Ids获取商品（api接口调用）
    * Data：2018-11-04 17:42
    */
    public List<ProductInfo> findListByIdIn(List<String> productIds){
        return dao.findByProductIdIn(productIds);
    }
}
